//
//  CQNetworkTool.swift
//  swift-weibo
//
//  Created by 陈乾 on 15/10/28.
//  Copyright © 2015年 陈乾. All rights reserved.
//

import UIKit
import AFNetworking

enum CQNetWorkLoadError: Int {
    case emptyToken = -1
    case emptyUid = -2
    
    var description :String
        {
        get
        {
            switch self
            {
            case CQNetWorkLoadError.emptyToken:
                return "没有access_Token"
            case CQNetWorkLoadError.emptyUid:
                return "没有Uid"
            }
            
        }
    }
    
    func error() ->NSError{
        return NSError(domain: "itcast.swift-weibo", code: rawValue, userInfo: ["errorDescription" : description])
    }
    
}

class CQNetworkTool: NSObject {
    
    private var afManager = AFHTTPSessionManager()
    //1.pod把第三方引进来 引入之前记得要提交代码到git一次
    //2.记得要引入头文件AFNetworking 让这个类继承 AFNetworking。。
    //3.创建单例
    static let shareInstance: CQNetworkTool = CQNetworkTool()
    
    override init() {
        
        let baseStr = "https://api.weibo.com/"
        let baseURL = NSURL(string: baseStr)
        //基本url
        afManager = AFHTTPSessionManager(baseURL: baseURL)
        //请求json的格式
        afManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
        
    }
    
    //    static let shareInstance: CQNetworkTool = {
    //        //获得微博的基础url（前面的url）
    //        let urlStr = "https://api.weibo.com/"
    //        let  tool = CQNetworkTool(baseURL: NSURL(string: urlStr))
    //        //给第三方添加一个 文件格式
    //        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
    //        return tool
    //        }()
    
    //1.去开发者网站 创建应用
    //2.拿请求网址和appKey 回调地址 拼接成字符串
    //3.写一个函数传入字符串 返回url
    
    private let client_id = "1458512798"
    let redirect_uri = "http://www.baidu.com/"
    private let client_secret = "8f254231bd2aef248cb2b64b19b9eff6"
    private let grant_type = "authorization_code"
    
    
    //MARK: -  返回请求的URL
    func getOauthUrl() ->NSURL
    {
        //拼接好路径
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        //拆包返回URL
        return NSURL(string: urlString)!
    }
    //MARK: - 加载AccessToken
    /**
    
    - parameter code:     传进来的code来获取数据的
    - parameter finished: 完成后的闭包回调把结果和错误传递出去
    - parameter erroe:
    */
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ())
    {
        let urlStr = "oauth2/access_token"
        //搞一个参数字典
        let paraDic = [
            "client_id": client_id,
            "redirect_uri": redirect_uri,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code":code
        ]
        
        //post 网络请求
        afManager.POST(urlStr, parameters: paraDic, success: { (_, result) -> Void in
            
//            print("result:\(result)")
            finished(result: result as? [String: AnyObject], error: nil)
            })
            { (_, error: NSError) -> Void in
                finished(result: nil, error: error)
                print(error)
        }
        
        
    }
    
    
    
    //MARK: -  根据url 加载用户数据 --用户名 用户头像
    //网络请求下来的数据结果 应该丢给调用者管理 所以用闭包
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ())
    {
        //        if var paraDict = tokenWhetherEmpty() {
        //            //自己定义一个错误
        //            let error = CQNetWorkLoadError.emptyToken.error()
        //            finished(result: nil, error: error)
        //            return
        //        }
        
        guard var paraDict = tokenWhetherEmpty() else {
            //自己定义一个错误
            let error = CQNetWorkLoadError.emptyToken.error()
            finished(result: nil, error: error)
            return
        }
        
        if CQUserAccount.loadAccount()?.uid == nil {
            print("没有uid")
            return
        }
        //请求的url字符串
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        //参数字典
        //        let paraDict = [
        //            "access_token":CQUserAccount.loadAccount()!.access_token!,
        //            "uid":CQUserAccount.loadAccount()!.uid!
        //        ]
        paraDict["uid"] = CQUserAccount.loadAccount()!.uid!
        //调用封装好的GET方法
        requestGET(urlStr, parameters: paraDict, finished: finished)
    }
    //MARK: - 加载网络上的微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        guard var ParaDict = tokenWhetherEmpty() else
        {
            
            //来这来说明token没有值 把自定义的错误信息回调回去
            let error = CQNetWorkLoadError.emptyToken.error()
            finished(result: nil, error: error)
            return
        }
        
        if since_id > 0 {
         ParaDict["since_id"] = since_id
        }
        else if max_id > 0 {
        ParaDict["max_id"] = max_id - 1
        }
        
        let urlStr = "2/statuses/home_timeline.json"
        
        requestGET(urlStr, parameters: ParaDict) { (result, error) -> () in
            finished(result: result, error: nil)
           
            
        }

    }
    
    //MARK: - 发送不带图片的微博
    func sendStatus(status: String, finished:(result: [String: AnyObject]?, error: NSError?) -> ()) {
      
        guard var ParaDict = tokenWhetherEmpty() else
        {
            //来这来说明token没有值 把自定义的错误信息回调回去
            let error = CQNetWorkLoadError.emptyToken.error()
            finished(result: nil, error: error)
            return
        }
        
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        ParaDict["status"] = status
        afManager.POST(url, parameters: ParaDict, success: { (_, result) -> Void in
            finished(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
            finished(result: nil, error: error)
        }
    
    
    }
    
    
    //MARK: - 判断access_Token是否有值 若妹纸就返回nil 有值就返回字典 这个字典里面有一个access_Token的键值对
    func tokenWhetherEmpty() ->[String: AnyObject]? {
        if CQUserAccount.loadAccount()?.access_token == nil {
            
            return nil
        }
        
        return ["access_token": CQUserAccount.loadAccount()!.access_token!]
        
    }
    
    //MARK: - GET请求的封装
    func requestGET(URLString: String, parameters: AnyObject?,finished: (result: [String: AnyObject]?, error: NSError?) -> ())
    {
        afManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
            
            finished(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                
                finished(result: nil, error: error)
        }
    }
    
    /*******End*******/
}
